export const formatExams = (data) => {
  let exams = [];
  let answers = [];

  try {
    exams = JSON.parse(data.exams);
    exams = exams.map((item, index) => {
      try {
        item.options = JSON.parse(item.options);
      } catch (error) {
        item.options = [];
      }
      return {
        ...item,
      };
    });
  } catch (error) {}

  try {
    answers = JSON.parse(data.answers);
  } catch (error) {}

  return {
    exams,
    answers,
  };
};

export const calcResult = (dataList, userList) => {
  let num = 0;

  dataList.forEach((element, index) => {
    const { type, correctAnswers } = element;

    const userAnswers = userList[index];

    if (type.trim()  === "单选题") {
      if (userAnswers === correctAnswers) {
        num++;
      }
    } else if (type.trim()  === "多选题") {
      try {
        const correctAnswersStr = correctAnswers.sort().join("");

        if (userAnswers === correctAnswersStr) {
          num++;
        }
      } catch (error) {}
    }
  });

  const percent = (num / dataList.length) * 100;

  const isInteger = percent % 1 === 0; // 判断是否为整数
  const formattedPercent = isInteger ? percent : parseFloat(percent.toFixed(1));

  return {
    num,
    percent: formattedPercent,
  };
};

export const calcStatus = (dataList, userList) => {
  dataList.forEach((element, index) => {
    const { type, correctAnswers } = element;
    let userAnswers = userList[index];

    console.log("type", type.trim() === "多选题", type, correctAnswers, userAnswers, correctAnswers === userAnswers);

    if (type.trim() === "单选题") {
      if (!userAnswers) {
        element.status = "empty";
      } else {
        element.status = userAnswers == correctAnswers ? "success" : "error";
      }
    } else if (type.trim() === "多选题") {
      try {
        userAnswers = userAnswers.sort().join("");
        if (!userAnswers) {
          element.status = "empty";
        } else {
          element.status = userAnswers == correctAnswers ? "success" : "error";
        }
      } catch (error) {}
    }
  });

  return dataList;
};

export const calcInitUserList = (dataList) => {
  const userAnswers = [];

  if (Array.isArray(dataList)) {
    dataList = dataList.map((item, index) => {
      if (item.type.trim() === "多选题") {
        userAnswers[index] = [];
      } else {
        userAnswers[index] = "";
      }
    });
  }

  return userAnswers;
};
